<?php
/**
 * Author:   tangxiaowen
 * Email:    846506584@qq.com
 * Date:     2019/4/22 0022
 * Describe: 滴滴风控
 */

namespace app\index\controller\didi;

use think\Log;
use think\Controller;
use think\Request;
use app\index\controller\Member;
use app\index\controller\System;

class Didi extends Controller
{
    //滴滴模型号
    private static $modelName;
    //滴滴请求地址
    private static $url = 'http://47.93.185.26/risk/gzip/';

    public function __construct()
    {
        parent::__construct();

        //日志初始化保存地址
        $requestName = Request::instance()->module();
        $controllerName = Request::instance()->controller();
        $action = Request::instance()->action();
        $setPath = strtolower("{$requestName}/{$controllerName}/{$action}/");
        Log::init(['path'=>LOG_PATH.$setPath,'type'  => 'file',]);

        //初始化滴滴配置
        $this->initDidiConfig();

        //校验系统环境
        $result = (new System())->checkSysTem();
        if(!$result){
            returnErrorResult('系统欠费，停止使用');
        }
    }

    /**
     * 测试方法
     */
    public function test()
    {
        $result = $this->didi(1070,'2019-04-22 10:20:55');
        dump($result);
    }

    /**
     * 请求滴滴风控地址并获取滴滴结果
     * @param integer $userId 用户ID
     * @param datetime $ApplyTime 申请借款时间
     * @param string $phoneOs 用户手机手机操作系统 android/ios
     * @param string $deviceId 设备号 ios填idfa，android填imei
     * @param integer $firstLoan 用户是否首贷 1是 0复贷
     */
    public function didi($userId,$ApplyTime,$firstLoan = 1,$phoneOs = '',$deviceId = '')
    {
        //获取用户数据 用户信息 社交信息 魔蝎原始数据 运营商数据
        $memberObj = new Member();
        $userInfo = $memberObj->getUserInfo($userId);
        $social = $memberObj->getUserSocial($userId);
        $moxie = $memberObj->getMoXieJson($userId);
        $merchant = $memberObj->getCarrierReportStr($userId);


        $phoneList1 =json_decode($social['Phonelist'],true);
        $phoneList2 = json_decode($phoneList1['mailList'],true);
        //组合请求参数请求滴滴风控并获取处理结果返回
        $temp = [
            'model_name' => self::$modelName,          //分配的模型号，对接时候进行分配
            'first_loan' => $firstLoan,
            'apply_time' => $ApplyTime,                //申请借款时间
            'mobile'     => $userInfo['Mobile']??'',   //手机号
            'name'       => $userInfo['TrueName']??'', //姓名
            'idcard'     => $userInfo['IDCard']??'',   //省份证号
            'user_address' => ($social['address']??'') . ($social['ad_detail']??''),
            'phone_os'   => $phoneOs,
            'device_id'  => $deviceId,
            'e_contacts' => [                          //紧急联系人 2位
                [
                    'contact_name'  => $social['person_one']??'',
                    'contact_phone' => $social['person_one_mobile']??'',
                ],
                [
                    'contact_name'  => $social['person_two']??'',
                    'contact_phone' => $social['person_two_mobile']??'',
                ]
            ],
            'carrier_data' => [
                'mx_raw'   => $moxie,                      //魔蝎原始数据
                'mx_report'=> $merchant['ReportData']??'', //魔蝎报告
            ],
            'contact'      => $phoneList2??'',
        ];

        $param1 = json_encode($temp,JSON_UNESCAPED_UNICODE);
        $param2 = gzencode($param1);

        $result1 = $this->curlRequest(self::$url,$param2);
        $result2 = json_decode($result1,true);
        if($result2 && $result2['return_code'] == 0){
            returnSuccessResult($result2);
        }else{
            returnErrorResult();
        }
    }

    /**
     * 获取滴滴配置信息
     * @return array
     */
    private function initDidiConfig()
    {
        $data = db('sys_integrate')->alias('i')
            ->join('xb_sys_inteparameter n','i.ID = n.IntegrateID')
            ->where(['i.EName' => 'didi'])
            ->find();

        if(!$data){
            returnErrorResult('尚未配置滴滴数据');
        }

        if(!isset($data['ParaName']) || empty($data['ParaName'])){
            returnErrorResult('尚未配置模型号');
        }elseif(!isset(self::$url) || empty(self::$url)){
            returnErrorResult('尚未配置滴滴请求地址');
        }

        self::$modelName  = $data['ParaValue'];
    }

    /**
     * 创建curl请求
     * @param url $url 请求地址
     * @param array $param 请求数据
     */
    public function curlRequest($url,$param)
    {
        $headers[] = "Content-Type:application/json";

        $culObj = curl_init();
        //设置请求的curl
        curl_setopt($culObj, CURLOPT_URL, $url);
        //不输出文件头(直接获取内容部分)
        curl_setopt($culObj, CURLOPT_HEADER, false);
        //设置curl请求方式
        curl_setopt($culObj, CURLOPT_POST, true);
        //设置请求的参数
        curl_setopt($culObj, CURLOPT_POSTFIELDS, $param);
        //将curl_exec()获取的信息以字符串返回，而不是直接输出。
        curl_setopt($culObj, CURLOPT_RETURNTRANSFER, true);
        //禁止 cURL 验证对等证书（peer's certificate）
        curl_setopt($culObj, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($culObj, CURLOPT_HTTPHEADER, $headers);
        //允许Curl函数执行的最长秒数。这里设置为30秒
        curl_setopt($culObj, CURLOPT_TIMEOUT, 30);
        $result = curl_exec($culObj);
        curl_close($culObj);

        return $result;
    }

}